package com.LGF.Book.action;

import com.LGF.Book.bean.Member;
import com.LGF.Book.bean.Record;
import com.LGF.Book.biz.MemberBiz;
import com.LGF.Book.biz.RecordBiz;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet("/record.let")
public class RecordServlet  extends HttpServlet {
    RecordBiz recordBiz = new RecordBiz();
    MemberBiz memberBiz = new MemberBiz();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    /**
     * /record.let?type=add&memId=xx 添加一条记录信息
     * /record.let?type=queryback&memId=xx 根据会员id查询会员借阅信息
     * /record.let?type=query&memId=xx 根据会员查询借阅记录信息
     * /record.let?type=keep&id=xx  根据id完成续借图书功能
     * /record.let?type=back&id=x  根据id完成批量归还功能
     * /record.let?type=selectAll  查询所有记录信息
     * /record.let?type=select  查询所有记录信息
     * /record.let?type=rentpre&memId=xx  会员页面借阅前准备
     * /record.let?type=selectBymemId&memId=xx 会员页面查询所有借阅信息
     * /record.let?type=mem_add&memId=xx 会员页面查询所有借阅信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //创建输出流对象,打印信息
        PrintWriter out = resp.getWriter();

        //创建session对象
        HttpSession session = req.getSession();
        String type = req.getParameter("type");

        Member member = (Member)session.getAttribute("member");

//        //验证用户是否登录
//        if (session.getAttribute("member")==null){
//            out.println("<script>alert('请登录');location.href='login.jsp';</script>");
//        }

        switch (type){
            case "add":
                add(req,resp,out);
                break;
            case"mem_add":
                mem_add(req,resp,out);
                break;
            case"queryback":
                queryback(req,resp,out);
                break;
            case "back":
                back(req,resp,out);
                break;
            case "query":
                query(req,resp,out);
                break;
            case"keep":
                keep(req,resp,out);
                break;
                
            case "selectAll":
                selectAll(req,resp,out);
                break;
            case "select":
                select(req,resp,out);
                break;

                //用户页面的Servlet
            case "rentpre":
                rentpre(req,resp,out);
                break;

            case "selectBymemId":
                selectBymemId(req,resp,out);
                break;
        }
    }

    /**
     * 实现会员页面图书借阅功能的实现
     * @param req
     * @param resp
     * @param out
     */
    private void mem_add(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        //接收前端传过来的memId值 和选中的id值
        long memId = Long.parseLong(req.getParameter("memId"));
        String ids = req.getParameter("ids");
        System.out.println("ids:"+ids);
        //把json字符串剪切成id 存入数组
        String[] strs = ids.split("_");
        System.out.println("strs"+strs);
        //创建long类型数组 存放bookId值
        List<Long> bookIds = new ArrayList<Long>();
        for (String s :strs){
            //把字符串转成long类型
            long id = Long.parseLong(s);
            //装进数组
            bookIds.add(id);
        }
        //获取当前负责处理借阅信息的会员编号
        HttpSession session = req.getSession();
        Member member = (Member)session.getAttribute("mem");

        //会员页面
        //调用biz层 判断图书是否有借阅信息
        int count = recordBiz.getById(memId, bookIds);
        System.out.println("count:"+count);
            if (count>0){
                //说明记录表里有了这个图书信息，会员借了某本书并且未归还
                out.println("<script>alert('您已经借了选中的书籍');location.href='record.let?type=rentpre&memId="+memId+"';</script>");
            }
            else{
                int count2 = recordBiz.add(memId, bookIds, member.getUserId());
                System.out.println("count2:"+count2);
                if (count2>0){
                    out.println("<script>alert('图书借阅成功');parent.location.href='user_Main.jsp';</script>");
                }
                else {
                    out.println("<script>alert('图书借阅失败');parent.location.href='user_Main.jsp';</script>");
                }
            }



    }

    /**
     * 会员页面根据会员id 查询所有借阅信息
     * @param req
     * @param resp
     * @param out
     */
    private void selectBymemId(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        //接收前端传过来的memId 和page ，limit
        long memId = Long.parseLong(req.getParameter("memId"));
        int page = Integer.parseInt(req.getParameter("page"));
        int limit = Integer.parseInt(req.getParameter("limit"));

        int pageIndex= (page-1)*limit;
        //调用biz层 根据id分页查询借阅信息
        List<Map<String, Object>> data = recordBiz.getByPageMemId(memId, pageIndex, limit);

        //调用biz层 根据id获取会员的所有借阅信息
        List<Map<String, Object>> all = recordBiz.selectByMemId(memId);

        System.out.println("data::"+data);
        System.out.println("data all::"+all);
        //创建JSONObject对象
        JSONObject json = new JSONObject();
        json.put("data",data);
        json.put("code",0);
        json.put("count",all.size());

        //打印
        out.print(json);



    }

    /**
     * 会员页面借阅图书前准备
     * @param req
     * @param resp
     * @param out
     */
    private void rentpre(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws ServletException, IOException {
        //获取前端穿过来的memId值
        long memId = Long.parseLong(req.getParameter("memId"));
        System.out.println(memId);
        //根据memId获取会员对象信息
        Member member = memberBiz.getById(memId);

        if (member!=null){
            //调用recordbiz层根据会员Id 查询会员的记录信息
            List<Record> records = recordBiz.getRecordByMemberId(member.getId());

            System.out.println(member);
            //进行判断会员是否借过书 是的话可借数量减少，没有借保持不变
            if (records.size()>0){
                //说明借过书籍 可借数量 - 记录的条数
                long size = member.getType().getAmount() - records.size();
                System.out.println(size);
                //重新设置可借数量
                member.getType().setAmount(size);
            }

            //存为session对象中
            HttpSession session2 = req.getSession();
            session2.setAttribute("mem",member);
            //转发
            req.getRequestDispatcher("mem_book_rent.jsp").forward(req,resp);

//            //把member对象 转给json字符串 传给前端
//            String json = JSON.toJSONString(member);
//
//
//            System.out.println(json);
//
//            //打印
//            out.print(json);
        }
        else{
            //转发
//            out.print("false");
            out.println("<script>alert('发生异常！');parent.location.href='user_Main.jsp';</script>");
        }


    }

    /**
     * 实现多添加查询记录信息功能
     * @param req
     * @param resp
     * @param out
     */
    private void select(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        //接收前端传过来的search值 page 和 limit
        String search = req.getParameter("search");
        int page = Integer.parseInt(req.getParameter("page"));
        int limit = Integer.parseInt(req.getParameter("limit"));
        int pageIndex =(page-1)*limit;

        //调用biz层多条件分页查询记录信息
        List<Map<String, Object>> data = recordBiz.conditionSearchByPage(pageIndex, limit, search);

        //调用biz层方法多条件查询记录信息
        List<Map<String, Object>> all = recordBiz.conditionSearch(search);

        //创建JSONObject对象
        JSONObject json = new JSONObject();
        json.put("data",data);
        json.put("code",0);
        json.put("count",all.size());

        //打印
        out.print(json);


    }

    /**
     * 实现显示所有记录信息
     * @param req
     * @param resp
     * @param out
     */
    private void selectAll(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        //接收前端传过来的page 和limit值
        int page = Integer.parseInt(req.getParameter("page"));
        int limit = Integer.parseInt(req.getParameter("limit"));
        int pageIndex=(page-1)*limit;
        //调用biz层 分页查询记录信息
        List<Map<String, Object>> data = recordBiz.getByPage(pageIndex, limit);
        //调用biz层，查询所有记录信息
        List<Map<String, Object>> all = recordBiz.searchAll();
        //创建json对象
        JSONObject json = new JSONObject();
        json.put("data",data);
        json.put("code",0);
        json.put("count",all.size());

        //打印转发
        out.print(json);


    }

    /**
     * 完成批量归还功能
     * @param req
     * @param resp
     * @param out
     */
    private void back(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        //接收前端传过来的ids字符串和memId值
        String ids = req.getParameter("ids");
        long memId = Long.parseLong(req.getParameter("memId"));
        //把json字符串剪切成id 存入数组
        String[] strs = ids.split("_");
        List<Long> recordIds = new ArrayList<Long>();
        for (String s:strs){
            long l = Long.parseLong(s);
            recordIds.add(l);
        }
        //获取当前负责处理借阅信息的会员编号
        HttpSession session = req.getSession();
        Member member = (Member)session.getAttribute("member");
        //获取操作的用户编号
        long userId = member.getPower().getId();

        if(userId==1){
            //归还
            //调用biz层修改信息
            int count = recordBiz.modify(memId, recordIds, userId);
            //判断是否归还成功
            if (count>0){
                out.println("<script>alert('归还成功');parent.location.href='admin_Main.jsp';</script>");
            }else {
                out.println("<script>alert('归还失败');parent.location.href='admin_Main.jsp';</script>");
            }
        }
        else if(userId==2){
            //userId =2 说明是会员页面 需要操作完成需要把操作人改为管理员
            userId=1;
            System.out.println("赋值后userId:"+userId);
            //归还
            //调用biz层修改信息
            int count = recordBiz.modify(memId, recordIds, userId);
            //判断是否归还成功
            if (count>0){
                out.println("<script>alert('归还成功');parent.location.href='admin_Main.jsp';</script>");
            }else {
                out.println("<script>alert('归还失败');parent.location.href='admin_Main.jsp';</script>");
            }
        }



    }

    /**
     * 完成续借功能
     * @param req
     * @param resp
     * @param out
     */
    private void keep(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        //接收前端传过来的id值
        long id = Long.parseLong(req.getParameter("id"));
        //调用biz层根据id修改归还日期
        int count = recordBiz.modify(id);
        //判断是否归还成功
        if (count>0){
            out.println("<script>alert('续借成功');parent.location.href='admin_Main.jsp';</script>");
        }
        else{
            out.println("<script>alert('续借失败');parent.location.hrefs='admin_Main.jsp';</script>");
        }


    }

    /**
     * 实现根据会员查询借阅信息功能 显示提供分页
     * @param req
     * @param resp
     * @param out
     */
    private void query(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        //接收前端传过来的memId值
        long memId = Long.parseLong(req.getParameter("memId"));
        //获取前端传过来的page和 limt值

        int page = Integer.parseInt(req.getParameter("page"));
        int limit = Integer.parseInt(req.getParameter("limit"));
        int pageIndex = (page-1)*limit;
        //调用biz层 根据会员id查询会员借阅信息
        List<Record> records = recordBiz.getPageByMemId(memId, pageIndex, limit);

        List<Record> all = recordBiz.getAllMemId(memId);
        //创建JSON对象
        JSONObject json = new JSONObject();
        json.put("data",records);
        json.put("code",0);
        json.put("count",all.size());

        System.out.println("@@@@"+records);
        //打印
        out.print(json);



    }

    /**
     * 查询会员借阅信息并返回json类型
     * @param req
     * @param resp
     * @param out
     */
    private void queryback(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws ServletException, IOException {
        //获取前端传过来的memId
        long memId = Long.parseLong(req.getParameter("memId"));
        //获取会员对象和所有未归还的记录
        //根据memId获取会员对象信息
        Member member = memberBiz.getById(memId);

        if (member!=null){
            List<Record> records = recordBiz.getRecordByMemberId(member.getId());
            System.out.println(records.size());
            long amount = records.size();
            //重新设置可借数量
            member.getType().setAmount(amount);
            System.out.println(member);
          //  把member对象 转给json字符串 传给前端
            String json = JSON.toJSONString(member);


            System.out.println(json);

            //打印
            out.print(json);

            //存入request
//            req.setAttribute("mem",member);
//            req.setAttribute("records",records);
           // System.out.println("record::::"+records.size());
           // System.out.println("member:"+member);
          //  System.out.println("records:"+records);
            //转发
           // req.getRequestDispatcher("book_return.jsp").forward(req,resp);
//
//            System.out.println(records);
//            //把records对象 转给json字符串 传给前端
//            String json = JSON.toJSONString(records);
//
//            System.out.println(json);
//            //打印
//            out.print(json);

        }else{
            //转发
            out.print("false");
        }




    }

    /**
     * 实现借阅功能
     * @param req
     * @param resp
     * @param out
     */
    private void add(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {

        //接收前端传过来的memId值 和选中的id值
        long memId = Long.parseLong(req.getParameter("memId"));
        String ids = req.getParameter("ids");
        System.out.println("ids:"+ids);
        //把json字符串剪切成id 存入数组
        String[] strs = ids.split("_");
        //创建long类型数组 存放bookId值
        List<Long> bookIds = new ArrayList<Long>();
        for (String s :strs){
            //把字符串转成long类型
            long id = Long.parseLong(s);
            //装进数组
            bookIds.add(id);
        }
        //获取当前负责处理借阅信息的会员编号
        HttpSession session = req.getSession();
        Member member = (Member)session.getAttribute("member");
        long userId = member.getPower().getId();
            //管理员页面
            //调用biz层 判断图书是否有借阅信息
            int count = recordBiz.getById(memId, bookIds);
            System.out.println("count:"+count);
            if (count>0){
                //说明记录表里有了这个图书信息，会员借了某本书并且未归还
                out.println("<script>alert('您已经借了选中的书籍');location.href='book_rent.jsp';</script>");
            }
            else{
                //调用recordbiz层根据会员卡号、书籍编号、用户类型编号添加记录信息1
                int count2 = recordBiz.add(memId, bookIds, userId);
                if (count2>0){
                    out.println("<script>alert('图书借阅成功');parent.location.href='admin_Main.jsp';</script>");
                }
                else {
                    out.println("<script>alert('图书借阅失败');parent.location.href='admin_Main.jsp';</script>");
                }
            }






    }
}
